package pomodorotasks

import ca.odell.glazedlists.EventList
import ca.odell.glazedlists.event.ListEventListener
import ca.odell.glazedlists.event.ListEvent

class PomodoroTasksListController {
    // these will be injected by Griffon
    def model
    def view
    
    GoogleTasksService googleTasksService

    void mvcGroupInit(Map args) {
        model.list = args.list
        installTaskListListener(model.tasksList)
        execOutside {
            updateTasksList()
        }
        
    }
    
    def installTaskListListener(EventList list) {
        list.addListEventListener( { event ->
                log.debug "Event: $event"
                while (event.next()) {
                    int index = event.getIndex()
                    int eventType = event.type
                    ListEvent eventCopy = event.copy()
                    execOutside {
                        if (eventType == ListEvent.UPDATE) {
                            googleTasksService.updateTask(model.list, list.get(index))
                            updateTasksList()
                        }
                    }
                }
            } as ListEventListener)
    }
    
    def updateTasksList() {
        def tasks = googleTasksService.getTasks(model.list).items
        model.tasksList.clear()
        model.tasksList.addAll(tasks)
    }

    def addAction = {
        execOutside {
            log.debug('Adding task')
            model.tasksList.add(googleTasksService.addTask(model.list))
        }
    }
    
}
